<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true" class="title_form">
        <el-form-item label="用户名:">
          <el-input />
        </el-form-item>
        <el-form-item>
          <el-button type="primary">搜索</el-button>
          <el-button>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin: 10px 0px">
      <el-button type="primary" @click="addUserInfo">添加用户</el-button>
      <el-button type="danger">批量删除</el-button>
      <el-table :data="userList" style="margin: 10px 0px" border>
        <el-table-column type="selection" width="55px" align="center" />
        <el-table-column type="index" width="50px" label="#" align="center" />
        <el-table-column label="ID" prop="id" align="center" />
        <el-table-column label="用户名" prop="name" align="center" />
        <el-table-column label="用户昵称" prop="username" align="center" />
        <el-table-column label="用户角色" prop="roleName" align="center" />
        <el-table-column label="创建时间" prop="createTime" align="center" />
        <el-table-column label="更新时间" prop="updateTime" align="center" />
        <el-table-column label="操作" align="center" width="300px">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              icon="User"
              size="small"
              @click="editUserRole(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="warning"
              icon="Edit"
              size="small"
              @click="editUserInfo(row)"
            >
              编辑
            </el-button>
            <el-button type="danger" icon="Delete" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        layout="prev, pager, next, jumper, ->,sizes,total"
        background="true"
        :total="pageTotal"
        @size-change="getUserPageData(1)"
        @current-change="getUserPageData"
      />
    </el-card>
    <!--左侧弹出框---->
    <el-drawer
      v-model="drawer"
      close-on-click-modal="false"
      close-on-press-escape="false"
    >
      <template #header>
        <h4>{{ userInfo.id ? '修改用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <div>
          <el-form
            :model="userInfo"
            ref="ruleFormRef"
            :rules="rules"
            label-position="right"
            label-width="auto"
          >
            <el-form-item label="用户名" prop="name">
              <el-input
                v-model="userInfo.name"
                placeholder="请输入用户名"
                :disabled="userInfo.id ? true : false"
              />
            </el-form-item>
            <el-form-item label="用户昵称" prop="username">
              <el-input
                v-model="userInfo.username"
                placeholder="请输入用户昵称"
              />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="!userInfo.id">
              <el-input v-model="userInfo.password" placeholder="请输入密码" />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelDrawer">取消</el-button>
          <el-button type="primary" @click="submitUserInfo(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
    <!--角色分配弹出框-->
    <el-drawer v-model="roleDrawer">
      <template #header>
        <h4>角色分配</h4>
      </template>
      <template #default>
        <div>
          <el-form :model="userInfo">
            <el-form-item label="用户名" prop="name">
              <el-input v-model="userInfo.name" disabled="false" />
            </el-form-item>
            <el-form-item label=" 职位列表">
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
                全选
              </el-checkbox>
              <el-checkbox-group
                v-model="userRoles"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="role in allRoles"
                  :key="role.id"
                  :label="role"
                  :value="role"
                >
                  {{ role.roleName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelRoleDrawer">取消</el-button>
          <el-button type="primary" @click="updateUserRole">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import { GetUserPageData, UpdateOrSaveUser } from '@/api/user'
import { GetRoleByUserID, UpdateUserRole } from '@/api/role'
import type {
  UserRoleData,
  UserRoleResponseData,
  UpdateUserRoleData,
} from '@/api/role/type'
import type { UserInfoResponsePageData, UserInfoRecord } from '@/api/user/type'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
//当前页
let currentPage = ref<number>(1)
//每页显示条数
let pageSize = ref<number>(5)
//总条数
let pageTotal = ref<number>(10)
//收集验证信息
const ruleFormRef = ref<FormInstance>()
//用户列表数据
let userList = ref<UserInfoRecord[]>()
//控制抽屉弹出与隐藏
let drawer = ref<boolean>(false)
let roleDrawer = ref<boolean>(false)
//收集用户角色
let userRoles = ref<UserRoleData[]>()
//收集所有用户角色
let allRoles = ref<UserRoleData[]>()
//定义全选框的中间状态
const isIndeterminate = ref<boolean>(true)
//是否选中全选框
const checkAll = ref<boolean>(false)
//收集用户填写的信息
let userInfo = reactive<UserInfoRecord>({
  id: null,
  username: '',
  name: '',
  password: '',
  createTime: '',
  updateTime: '',
  phone: '',
  roleName: '',
})
//向服务器提交数据
const submitUserInfo = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let result = await UpdateOrSaveUser(userInfo)
      if (result.code == 200) {
        ElMessage.success(`${userInfo.id ? '修改' : '添加'}成功`)
        getUserPageData(userInfo.id ? currentPage.value : 1)
      } else {
        ElMessage.error(`${userInfo.id ? '修改' : '添加'}成功`)
      }
      drawer.value = false
    } else {
      return false
    }
  })
}

const editUserInfo = (row: UserInfoRecord) => {
  drawer.value = true
  Object.assign(userInfo, row)
  nextTick(() => {
    ruleFormRef.value.clearValidate('username')
    ruleFormRef.value.clearValidate('name')
    ruleFormRef.value.clearValidate('password')
  })
}
//保存或修改用户
const addUserInfo = () => {
  Object.assign(userInfo, {
    id: null,
    username: '',
    name: '',
    password: '',
    createTime: '',
    updateTime: '',
    phone: '',
    roleName: '',
  })
  drawer.value = true
  nextTick(() => {
    ruleFormRef.value.clearValidate('username')
    ruleFormRef.value.clearValidate('name')
    ruleFormRef.value.clearValidate('password')
  })
}

//修改用户角色
const updateUserRole = async () => {
  let data: UpdateUserRoleData = {
    userId: userInfo.id as number,
    roleIdList: userRoles.value.map((item) => {
      return item.id as number
    }),
  }
  let result = await UpdateUserRole(data)
  if (result.code == 200) {
    ElMessage.success('分配职位成功')
    roleDrawer.value = false
  }
}
//关闭抽屉
const cancelDrawer = () => {
  drawer.value = false
}

const cancelRoleDrawer = () => {
  roleDrawer.value = false
}

//获取用户分页信息
const getUserPageData = async (pager: number = 1) => {
  currentPage.value = pager
  let result: UserInfoResponsePageData = await GetUserPageData(
    currentPage.value,
    pageSize.value,
  )
  pageTotal.value = result.data.total
  userList.value = result.data.records
}

//用户名验证
const validateName = (rule: any, value: any, callback: any) => {
  if (value.length < 5) {
    callback(new Error('用户名不能小于5位'))
  } else {
    callback()
  }
}

//用户昵称验证
const validatRealName = (rule: any, value: any, callback: any) => {
  if (value.length < 5) {
    callback(new Error('用户昵称不能小于5位'))
  } else {
    callback()
  }
}

//密码验证
const validatPassword = (rule: any, value: any, callback: any) => {
  if (value.length < 6) {
    callback(new Error('密码不能小于6位'))
  } else {
    callback()
  }
}

//定义自定义校验规则
const rules = reactive<FormRules<UserInfoRecord>>({
  name: [{ required: true, validator: validateName, trigger: 'blur' }],
  username: [{ required: true, validator: validatRealName, trigger: 'blur' }],
  password: [{ required: true, validator: validatPassword, trigger: 'blur' }],
})
//分配角色按钮回调
const editUserRole = async (data: UserInfoRecord) => {
  let result: UserRoleResponseData = await GetRoleByUserID(data.id as number)
  if (result.code == 200) {
    userInfo = data
    userRoles.value = result.data.assignRoles
    allRoles.value = result.data.allRolesList
    roleDrawer.value = true
  }
}
//选中全选按钮事件回调
const handleCheckAllChange = (val: boolean) => {
  userRoles.value = val ? allRoles.value : []
  isIndeterminate.value = false
}
//复选框选中的事件回调
const handleCheckedCitiesChange = (value: UserRoleData[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRoles.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRoles.value.length
}

onMounted(() => {
  getUserPageData()
})
</script>

<style scoped>
.title_form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
